define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var options = ["A","B","C","D","E","F","G"]
    // 重置答案
    var resetAns = {
        // 渲染单选按钮 答案
        radio:function(o){
            var html = ''
            // 拼接新的html
            var len = $('.fieldlist .form-inline').length
            var opt = options
            if(typeof o !== 'undefined'){
                len = o.length
                opt = o
            }

            for (let index = 0; index < len; index++) {
                html+='<label><input type="radio" value="'+index+'" name="row[answers][]">'+opt[index]+'</label>'
                
            }

            // 显示html
            $('#answer-box').html('<div class="radio">'+html+'</div>')
        },
        checkbox:function(){
            var html = ''
            // 拼接新的html
            var len = $('.fieldlist .form-inline').length
            var opt = options

            for (let index = 0; index < len; index++) {
                html+='<label><input type="checkbox" value="'+index+'" name="row[answers][]">'+opt[index]+'</label>'
                
            }

            // 显示html
            $('#answer-box').html('<div class="checkbox">'+html+'</div>')
        },
        judge:function(){
            this.radio(["对","错"])
        },
        textarea:function(){
            $('#answer-box').html('<textarea name="row[answers][]" class="form-control" rows="4"></textarea>')
        }
    }

    function changeAnswer(){
        var val = $('[name="row[typedata]"]:checked').val()
        if(val == 1){
            resetAns.radio()
        }
        else if(val == 2){
            resetAns.checkbox()
        }
        else if(val == 3){
            resetAns.judge()
        }
        else{
            resetAns.textarea()
        }
    }

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'questions/index' + location.search,
                    add_url: 'questions/add',
                    edit_url: 'questions/edit',
                    del_url: 'questions/del',
                    multi_url: 'questions/multi',
                    import_url: 'questions/import',
                    table: 'questions',
                }
            });

            var table = $("#table");

            console.log(Config);
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedNumber: 1,
                fixedRightNumber: 1,
                escape:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'course.name', title: __('Course.name'), operate: 'LIKE'},
                        {field: 'typedata', title: __('Typedata'), searchList: {"1":__('Typedata 1'),"2":__('Typedata 2'),"3":__('Typedata 3'),"4":__('Typedata 4'),"5":__('Typedata 5')}, formatter: Table.api.formatter.normal},
                        {field: 'title', title: __('Title'), operate: 'LIKE',cellStyle:function(){
                            return {
                                css:{
                                    // "display":"block",
                                    "overflow":"hidden"
                                }
                            }
                        },class: 'autocontent',formatter:Table.api.formatter.content},
                        
                        
                        {field: 'answerscontent', title: __('Answerscontent'), operate: 'LIKE',cellStyle:function(){
                            return {
                                css:{
                                    // "display":"block",
                                    "overflow":"hidden"
                                }
                            }
                        },visible:false,class: 'autocontent',formatter:Table.api.formatter.content},
                        {field: 'answers', title: __('Answers'), operate: 'LIKE', table: table, class: 'autocontent', formatter: function(value){
                            // console.log(value);
                            var v = value.replace(/&quot;/g,'"')
                            var arr = JSON.parse(v)
                            // console.log('arr: ', arr);
                            return arr.join(',')

                        }},

                        {field: 'diffdata', title: __('Diffdata'), searchList: {"1":__('Diffdata 1'),"2":__('Diffdata 2'),"3":__('Diffdata 3'),"4":__('Diffdata 4'),"5":__('Diffdata 5')}, formatter: Table.api.formatter.normal},

                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3')},custom:{1:'primary',2:'danger',3:'success'}, formatter: function(value, row, index){
                            // console.log('row: ', row);
                            var h = Table.api.formatter.status.call(this,value, row, index)
                            if(Config.can_change_status){
                                h+=' <button class="btn btn-xs btn-success btn-status-pass" data-id="'+row.id+'">通过</button> <button class="btn btn-xs btn-danger btn-status-reject" data-id="'+row.id+'">拒绝</button>'
                            }
                            return h
                        }},
                        {field: 'remark', title: __('Remark'), operate: 'LIKE', table: table, class: 'autocontent', formatter: function(v){
                            return v?v:'-'
                        }},
                        {field: 'admin_id', title: __('Admin_id'),visible:false},
                        
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function(value, row, index){
                            // Table.button.edit.visible = row.admin_id == Config.admin_id
                            Table.button.edit.visible = Config.admin_ids.includes(row.admin_id)
                            return Table.api.formatter.operate.call(this,value, row, index)
                        },buttons:[
                            {
                                name:'del',
                                text:'删除',
                                classname:'btn btn-xs btn-danger btn-ajax',
                                url:'questions/is_useing',
                                icon:'fa fa-trash',
                                visible:function(row){
                                    // admin_id == 当前用户
                                    // return row.admin_id == Config.admin_id
                                    return Config.admin_ids.includes(row.admin_id)
                                },
                                success:function(data,b){
                                    // console.log('a,b: ', data,b);
                                    // 未被占用，提示删除
                                    Layer.confirm(
                                        __('Are you sure you want to delete this item?'),
                                        {icon: 3, title: __('Warning'),shadeClose: true, btn: [__('OK'), __('Cancel')]},
                                        function (index) {
                                            Table.api.multi("del", data.ids, table);
                                            Layer.close(index);
                                        }
                                    );

                                    return false;
                                },  
                                error:function(data,ret){
                                    // 被占用了，提示是否确定要删除

                                    Layer.confirm(
                                        ret.msg,
                                        {icon: 3, title: __('Warning'),shadeClose: true, btn: [__('OK'), __('Cancel')]},
                                        function (index) {
                                            Table.api.multi("del", data.ids, table);
                                            Layer.close(index);
                                        }
                                    );

                                    return false;
                                },     
                            }
                        ]}
                    ]
                ]
            });

            $('.btn-del-checked').click(function (e) { 
                e.preventDefault();
                // console.log('批量删除');
                var ids = Table.api.selectedids(table)
                // console.log('ids: ', ids);
                layer.load(3)
                $.ajax({
                    type: "post",
                    url: 'questions/is_useing',
                    data: {
                        ids:ids.join(',')
                    },
                    dataType: "json",
                    success: function (response) {
                        // console.log('response: ', response);
                        var msg = response.code==1?__('Are you sure you want to delete this item?'):response.msg
                        Layer.confirm(
                            msg,
                            {icon: 3, title: __('Warning'),shadeClose: true, btn: [__('OK'), __('Cancel')]},
                            function (index) {
                                Table.api.multi("del", ids.join(','), table);
                                Layer.close(index);
                            }
                        );
                    },
                    complete:function(){
                        layer.closeAll('loading');
                    }
                });
            });

            // 审核
            var audit = {
                pass:function(id){
                    $.ajax({
                        type: "post",
                        url: "./questions/change_status/type/pass",
                        data: {
                            id:id
                        },
                        dataType: "json",
                        success: function (response) {
                            console.log('response: ', response);
                            if(response.code == 1){
    
                                table.bootstrapTable('refresh')
                            }
                            else{
                                layer.msg(response.msg)
                            }
                        }
                    });
                },
                reject:function(id){
                    layer.prompt({title: '请输入拒绝原因', formType: 2}, function(val, index){
                        // 
                        if(val.trim()!==''){
      
                          $.ajax({
                              type: "post",
                              url: "./questions/change_status/type/reject",
                              data: {
                                  id:id,
                                  remark:val.trim()
                              },
                              dataType: "json",
                              success: function (response) {
                                  console.log('response: ', response);
                                  
                                  if(response.code == 1){
                                      layer.close(index);
                                      table.bootstrapTable('refresh')
                                  }
                                  else{
                                      layer.msg(response.msg)
                                  }
                              }
                          });
                        }
      
                      });
                }
            }
            // 批量通过
            $('.btn-audit-pass').click(function (e) { 
                e.preventDefault();
                var ids = Table.api.selectedids(table)
                audit.pass(ids)
            })

            // 批量拒绝
            $('.btn-audit-reject').click(function (e) { 
                e.preventDefault();
                var ids = Table.api.selectedids(table)
                audit.reject(ids)
            })

            // 通过
            $(document).on('click','.btn-status-pass',function(){
                var id = $(this).data('id');
                console.log('通过id: ', id);
                audit.pass(id)
            })

            // 拒绝
            $(document).on('click','.btn-status-reject',function(){
                var id = $(this).data('id');
                console.log('拒绝id: ', id);
                audit.reject(id)
            })

            $(".btn-add-ai").click(function(e){
                e.preventDefault();
                Fast.api.open('questions/addai', "ai添加题目", {

                });
            })
            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        list: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'questions/index' + location.search,
                   
                    table: 'questions',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                escape:false,
                columns: [
                    [
                       
                        {field: 'id', title: __('Id')},
                        {field: 'course_id', title: __('Course_id'),visible:false},
                        {field: 'course.name', title: __('Course.name'), operate: 'LIKE'},
                        {field: 'typedata', title: __('Typedata'), searchList: {"1":__('Typedata 1'),"2":__('Typedata 2'),"3":__('Typedata 3'),"4":__('Typedata 4'),"5":__('Typedata 5')}, formatter: Table.api.formatter.normal},
                        {field: 'title', title: __('Title'), operate: 'LIKE',cellStyle:function(){
                            return {
                                css:{
                                    // "display":"block",
                                    "overflow":"hidden"
                                }
                            }
                        },class: 'autocontent',formatter:Table.api.formatter.content},
                        
                        

                        {field: 'diffdata', title: __('Diffdata'), searchList: {"1":__('Diffdata 1'),"2":__('Diffdata 2'),"3":__('Diffdata 3'),"4":__('Diffdata 4'),"5":__('Diffdata 5')}, formatter: Table.api.formatter.normal},
                                              
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,buttons:[
                            {
                                name:'addbtn',
                                text:'添加',
                                classname:'btn btn-success btn-xs btn-click',                                
                                visible:function(row){
                                    // 当题目不存在的时候，返回true
                                    return !parent.hasQuestionYet(row)
                                },
                                click:function(i,row){
                                    console.log('i,r: ', i,row);
                                    // 隐藏自己
                                    $(this).hide()
                                    parent.addQuestion(row)
                                }
                            }
                        ]}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'questions/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'questions/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'questions/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();

            $('[name="row[typedata]"]').change(function(){
                var val = $(this).val()
                console.log('val: ', val);
                if(val > 2){
                    // 隐藏选项
                    $('.option-box').hide()
                }
                else{
                    // 显示选项
                    $('.option-box').show()
                }

                changeAnswer()
            })

            $(document).on("fa.event.appendfieldlist", '[data-name="row[optionjson]"] .btn-append', function(e, obj){
                changeAnswer()
                let index = $('.fieldlist .form-inline').last().index()
                let val = options[index - 1]
                $('.fieldlist .form-inline').last().find('input:eq(0)').val(val)
            });

            $(document).on('click','.btn-remove',function(){
                changeAnswer()
            })

            // 设置为答案
            $(document).on('click','.btn-setanswer',function(){
                let index = $(this).parent().index()
                console.log('index: ', index);
                $('#answer-box label').eq(index-1).find('input').click()
                return false
            })
        },
        edit: function () {
            Controller.api.bindevent();

            var setAnsValue = {
                radio:function(v){
                    // .prop("checked",true)
                    $('#answer-box input[type="radio"][value="'+v[0]+'"]').prop("checked",true)
                },
                checkbox:function(v){
                    for(var i=0;i<v.length;i++){
                        $('#answer-box input[type="checkbox"][value="'+v[i]+'"]').prop("checked",true)
                    }
                },
                judge:function(v){
                    this.radio(v)
                },
                textarea:function(v){
                    $('#answer-box textarea').val(v[0])
                }
            }

            function changeAnswerValue(){
                var val = $('[name="row[typedata]"]:checked').val()
                var value = $('[name="row[answersvalue]"]').val()
                value = JSON.parse(value)

                if(val == 1){
                    setAnsValue.radio(value)
                }
                else if(val == 2){
                    setAnsValue.checkbox(value)
                }
                else if(val == 3){
                    setAnsValue.judge(value)
                }
                else{
                    setAnsValue.textarea(value)
                }
            }

            $('[name="row[typedata]"]').change(function(){
                var val = $(this).val()
                console.log('val: ', val);
                if(val > 2){
                    // 隐藏选项
                    $('.option-box').hide()
                }
                else{
                    // 显示选项
                    $('.option-box').show()
                }

                changeAnswer()
            })

            $(document).on("fa.event.appendfieldlist", '[data-name="row[optionjson]"] .btn-append', function(e, obj){
                changeAnswer()
                changeAnswerValue()

                let index = $('.fieldlist .form-inline').last().index()
                let val = options[index - 1]
                $('.fieldlist .form-inline').last().find('input:eq(0)').val(val)
            });

            $(document).on('click','.btn-remove',function(){
                changeAnswer()
            })

            // 设置为答案
            $(document).on('click','.btn-setanswer',function(){
                let index = $(this).parent().index()
                console.log('index: ', index);
                $('#answer-box label').eq(index-1).find('input').click()
                return false
            })

            // 判断 问答 填空
            // changeAnswerValue()
            var type = $('[name="row[typedata]"]:checked').val()

            if(type > 2){
                $('.option-box').hide()
                changeAnswer()
                changeAnswerValue()
            }
        },
        addai: function () {

            function getFormDataAsJson(formSelector) {
                const form = $(formSelector);
                const formDataArray = form.serializeArray();
                const jsonObject = {};

                formDataArray.forEach(item => {
                    if (jsonObject[item.name]) {
                        if (!Array.isArray(jsonObject[item.name])) {
                            jsonObject[item.name] = [jsonObject[item.name]];
                        }
                        jsonObject[item.name].push(item.value);
                    } else {
                        jsonObject[item.name] = item.value;
                    }
                });

                return jsonObject;
            }
            Controller.api.bindevent();  

            var eventSource = null
            function endDoSomething() {
                $('.content-box .loading-icon,.btn-ai-end').hide()
                eventSource.close();
                 $('.btn-ai-start').attr('disabled', false)
            }

            function extractJsonContent(contentText) {
                contentText = contentText.trim()
                const jsonPattern = /^```json([\s\S]*)```$/;
                const match = contentText.match(jsonPattern);
                
                if (match) {
                    // 如果匹配成功，返回中间的内容
                    return match[1].trim();
                } else {
                    // 如果不匹配，返回原样
                    return contentText;
                }
            }
            
            $('.btn-ai-start').click(function (e) { 
                e.preventDefault();
                $('.content-box,.content-box .loading-icon,.btn-ai-end').show()
                $('#content-result,#reasoning-result,#questions-list').empty()
                $('.btn-ai-start').attr('disabled', true)
                // 使用示例
                const formJson = getFormDataAsJson('#add-ai-form');
                // console.log(formJson);  
                const formJsonStr = new URLSearchParams(formJson).toString();
                // console.log('formJsonStr: ', formJsonStr);
                // 创建 EventSource 实例并传递参数
                if (eventSource) {
                    eventSource.close();
                }
                eventSource = new EventSource(`eventai?${formJsonStr}`);

                var contentText = ''
                var reasoningText = ''
                // 处理消息事件
                eventSource.onmessage = function(event) {
                    // console.log( event.data);
                    
                    let obj = JSON.parse(event.data)
                    if (obj.reasoning_content) {
                        reasoningText+=obj.reasoning_content
                        $("#reasoning-result").text(reasoningText)
                    }
                    else if (obj.content) {
                        
                        contentText+=obj.content
    
                        $("#content-result").text(contentText)
                    }
                  
                };

                // 处理错误事件
                eventSource.onerror = function(err) {
                    console.error('EventSource failed:', err);
                    endDoSomething()
                };

                eventSource.addEventListener('done', function () {
                    contentText = extractJsonContent(contentText)
                    
                    var list = []
                    JSON.parse(contentText).forEach((item,index) => {
                    list.push(`
                        <div class="list">
                            <div class="title">${index+1}.${item.question}</div>
                            <div class="options">${item.options.join('<br>')}</div>
                            <div class="answer">${item.answer.join('<br>')}</div>
                            <div class="jiexi">${item.jiexi}</div>
                        </div>
                        `)
                    })
                    // console.log('list: ', list);

                    $('#questions-list').html(list.join(''))
                    $('[name="row[questions]"]').val(contentText)

                    endDoSomething()
                })
                
            });

            $('.btn-ai-end').click(function (e) { 
                e.preventDefault();
                endDoSomething()
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
